<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">登录</div>
    <div class="login-form-sub-title"> 科秘档案CMyOffice </div>
    <div class="login-form-error-msg">{{ errorMessage }}</div>
    <a-form
      ref="loginForm"
      :model="userInfo"
      class="login-form"
      layout="vertical"
      @submit="handleSubmit"
    >
      <!-- 表单内容保持不变 -->
      <a-form-item
        field="username"
        :rules="[{ required: true, message: '请输入用户名' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input v-model="userInfo.username" placeholder="请输入" size="large">
          <template #prefix>
            <icon-user />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        field="password"
        :rules="[{ required: true, message: '请输入密码' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input-password
          v-model="userInfo.password"
          placeholder="请输入"
          allow-clear
          size="large"
        >
          <template #prefix>
            <icon-lock />
          </template>
        </a-input-password>
      </a-form-item>
      <a-space :size="16" direction="vertical">
        <div class="login-form-password-actions">
          <a-col :span="14">
            <a-form-item
              field="code"
              hide-label
              :rules="[
                { required: true, message: '请填写完整' },
                { minLength: 6, message: '请填写完整' },
              ]"
            >
              <a-verification-code v-model="userInfo.code" />
            </a-form-item>
          </a-col>
          <div>
            <canvas
              ref="domRef"
              @click="refreshCode"
              :width="130"
              :height="35"
              style="border: 1px solid #ddd; cursor: pointer"
            ></canvas>
          </div>
        </div>
        <div class="login-form-password-btn">
          <a-button type="primary" html-type="submit" long :loading="loading">
            确认
          </a-button>
          <a-button class="reset" @click="resetFormData"> 重置 </a-button>
        </div>
        <div>
          <a-checkbox
            checked="rememberPassword"
            :model-value="loginConfig.rememberPassword"
            @change="setRememberPassword as any"
          >
            记住密码
          </a-checkbox>
        </div>
      </a-space>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import { useStorage } from '@vueuse/core';
  import { useUserStore, useAppStore } from '@/store';
  import useLoading from '@/hooks/loading';
  import { useImageVerify } from '@/hooks/qrcode';
  import { isEmpty } from 'lodash';
  const { domRef, getImgCode } = useImageVerify(130, 35, '');

  const router = useRouter();
  const route = useRoute();
  const errorMessage = ref('');
  const { loading, setLoading } = useLoading();
  const userStore = useUserStore();
  const appStore = useAppStore();

  // 验证码相关
  const props = withDefaults(
    defineProps<{
      infoData: object;
    }>(),
    {
      infoData: () => {},
    }
  );
  const emits = defineEmits(['changeQrode']);

  function refreshCode() {
    emits('changeQrode');
  }

  watch(
    () => props.infoData,
    (newValue) => {
      if (!isEmpty(newValue) && newValue.captcha) {
        getImgCode(newValue.captcha);
      }
    },
    { immediate: true, deep: true }
  );

  // 登录配置缓存
  const loginConfig = useStorage('login-config', {
    rememberPassword: false,
    username: '',
    password: '',
  });

  const userInfo = reactive({
    username: loginConfig.value.username,
    password: loginConfig.value.password,
    rememberPassword: loginConfig.value.rememberPassword,
    code: '',
  });

  const resetFormData = () => {
    userInfo.username = '';
    userInfo.password = '';
    userInfo.code = '';
  };

  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (loading.value) return;
    if (!errors) {
      setLoading(true);
      try {
        const qres = {
          username: values.username,
          password: values.password,
          captcha: values.code,
          captcha_id: props.infoData.captcha_id,
        };
        await userStore.login(qres);
        await userStore.fetchAllData();
        await userStore.getUserInfo();

        // 处理跳转逻辑
        const { redirect, ...othersQuery } = route.query;
        let targetRoutePath = '';

        // 1. 检查是否有有效的redirect参数
        if (redirect && typeof redirect === 'string') {
          const foundRoute = findRouteByName(appStore.routes, redirect);
          if (foundRoute) {
            targetRoutePath = getRoutePathWithChildren(foundRoute);
          }
        }
        // 2. 检查是否有personal路由
        else {
          const personalRoute = findRouteByName(appStore.routes, 'personal');
          if (personalRoute) {
            targetRoutePath = getRoutePathWithChildren(personalRoute);
          }
          // 3. 跳转到路由列表的第一个有效路由（带children的取第一个child）
          else if (appStore.routes && appStore.routes.length > 0) {
            targetRoutePath = getRoutePathWithChildren(appStore.routes[0]);
          }
        }
        console.log('跳转的页面', targetRoutePath);
        // 执行跳转
        if (targetRoutePath) {
          router.push({
            path: targetRoutePath,
            query: { ...othersQuery },
          });
        } else {
          // 安全兜底
          router.push('/');
        }

        Message.success('登录成功');
        // 记住密码处理
        const { username, password } = values;
        loginConfig.value.username = loginConfig.value.rememberPassword
          ? username
          : '';
        loginConfig.value.password = loginConfig.value.rememberPassword
          ? password
          : '';
      } catch (err) {
        userInfo.code = '';
        refreshCode();
        errorMessage.value = (err as Error).message;
      } finally {
        setLoading(false);
      }
    }
  };

  const setRememberPassword = (value: boolean) => {
    loginConfig.value.rememberPassword = value;
  };

  // 查找路由是否存在
  function findRouteByName(routes, targetName) {
    if (!routes || !targetName) return null;

    for (const route of routes) {
      if (route.name === targetName) {
        return route;
      }

      if (route.children && route.children.length > 0) {
        const found = findRouteByName(route.children, targetName);
        if (found) return found;
      }
    }
    return null;
  }

  // 关键函数：如果路由有children，返回第一个child的path，否则返回自身path
  function getRoutePathWithChildren(route) {
    // 如果有子路由且子路由列表不为空，返回第一个子路由的path
    if (route.children && route.children.length > 0) {
      return route.children[0].path;
    }
    // 否则返回当前路由的path
    return route.path;
  }
</script>

<style lang="less" scoped>
  /* 样式保持不变 */
  .login-form {
    &-wrapper {
      width: 420px;
    }

    &-title {
      color: var(--color-text-1);
      font-weight: 500;
      font-size: 24px;
      line-height: 32px;
    }

    &-sub-title {
      color: var(--color-text-3);
      font-size: 16px;
      line-height: 24px;
    }

    &-error-msg {
      height: 32px;
      color: rgb(var(--red-6));
      line-height: 32px;
    }

    &-password-actions {
      display: flex;
      justify-content: space-between;
    }
    &-password-btn {
      display: flex;
      flex-direction: row;
      align-items: center;
      width: 100%;
      .reset {
        margin-left: 5px;
      }
    }

    &-register-btn {
      color: var(--color-text-3) !important;
    }
  }
</style>
